/**
 * Created by Administrator on 2018/2/26.
 */
import axios from 'axios'
import qs from 'qs'

//import * as _ from '../util/tool'

// axios 配置
if(localStorage.authtoken!=undefined){
  axios.defaults.headers['x-auth-token'] = JSON.parse(localStorage.authtoken).token;
}
axios.defaults.timeout = 100000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.defaults.baseURL = 'http://www.300.com';

//axios.defaults.baseURL = 'http://www.chuanding159.com/';


//POST传参序列化
axios.interceptors.request.use((config) => {
  /*console.log(config)*/
  if(config.method  === 'post'){
    config.data = qs.stringify(config.data);
  }
  if(localStorage.authtoken!==undefined){

    //config.headers.x-auth-token = gettoken();
    if(config.headers['x-auth-token'] !== gettoken()){
      config.headers['x-auth-token'] = gettoken();
    }
  }
  return config;
},(error) =>{

  return Promise.reject(error);
});

//返回状态判断
axios.interceptors.response.use((res) =>{
  /*  console.log(res)*/
//  if(!res.data.success){
////      _.toast(res.data.msg);
//      return Promise.reject(res);
//  }
  return res;
}, (error) => {
//  _.toast("网络异常", 'fail');
  return Promise.reject(error);
});
export function gettoken(){
  return JSON.parse(localStorage.authtoken).token;
}
export function fetchpost(url, params) {
  return new Promise((resolve, reject) => {
    axios.post(url, params)
      .then(response => {

        if(response.data.success==true){
          resolve(response.data);
        }
        else{
          reject(response.data);
        }

      }, err => {
        reject(err);
      })
      .catch((error) => {
        reject(error)
      })
  })
}

export function fetchget(url) {
  return new Promise((resolve, reject) => {
    axios.get(url)
      .then(response => {
        console.log()
        if(response.data.result=='success'){

          resolve(response.data);
        }
        else{
          reject(response.data);
        }
      }, err => {
        reject(err);
      })
      .catch((error) => {
        reject(error)
      })
  })
}

//import userapi from './userapi'
export default {
  //首页
  banner(data){
    return fetchpost('/api/index/banner',data)
  }
}



